<?php
declare(strict_types=1);

namespace app\middleware;

use think\Request;

class ApiSignCheck
{

    private const SIGN_KEY = 'HCZWFJZ2WX2021&#@_^*!';


    public function handle($request)
    {
        $params = request()->param();
        $result = $this->checkSign($params);
        if (empty($result)) {
            throw new \app\MyException(11101);
        }

        unset($params);

        return $handler->handle($request);
    }

    public function checkSign($params, $secret)
    {
        $sign = $params['sign'] ?? null;
        unset($params['sign']);
        $params['secret'] = $secret;

        return $sign && $sign == $this->doSign($params);
    }

    protected function doSign($params)
    {
        ksort($params);

        $paramsJoined = [];
        foreach($params as $param => $value) {
            $paramsJoined[] = "$param=$value";
        }
        $query = implode('&', $paramsJoined);

        return md5($query);
    }
}